package com.cloudkinto.service.replacement.impl;

import cn.afterturn.easypoi.csv.entity.CsvExportParams;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudkinto.common.DicBusinessConstant;
import com.cloudkinto.common.DicBusinessItemConstant;
import com.cloudkinto.common.constant.GlobalConstants;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.utils.*;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.dao.*;
import com.cloudkinto.entity.*;
import com.cloudkinto.extentity.output.OrderOutputProductRackDto;
import com.cloudkinto.service.company.CompanyService;
import com.cloudkinto.service.dic.DicBusinessItemService;
import com.cloudkinto.service.email.MailSenderService;
import com.cloudkinto.service.file.FileService;
import com.cloudkinto.service.finance.CostRecordService;
import com.cloudkinto.service.finance.vo.IdAndNameEntity;
import com.cloudkinto.service.orderoutput.vo.OrderOutputProductSortRes;
import com.cloudkinto.service.orderoutput.vo.OrderOutputSagawaExportVo;
import com.cloudkinto.service.orderoutput.vo.OrderOutputTrackNumberExcelImport;
import com.cloudkinto.service.orderoutput.vo.OrderOutputYamatoExportVo;
import com.cloudkinto.service.replacement.ReplacementService;
import com.cloudkinto.service.replacement.vo.*;
import com.cloudkinto.service.stock.StockRecordService;
import com.cloudkinto.service.storage.StorageService;
import com.cloudkinto.utils.FreeMarkerUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.Session;
import javax.mail.Transport;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author fanp
 * @version v1.0.0
 * @Description :
 * @Create on : 2021/4/13 17:22
 **/
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class ReplacementServiceImpl extends ServiceImpl<ReplacementDao, ReplacementDo> implements ReplacementService {
    @Autowired
    ReplacementDao dao;
    @Autowired
    OrderOutputDao orderOutputDao;
    @Autowired
    private FileService fileService;
    @Autowired
    private StorageDao storageDao;
    @Autowired
    private ProductInfoDao productInfoDao;
    @Autowired
    private OrderOutputProductDao productDao;
    @Autowired
    private CompanyDao mCompanyDao;
    @Autowired
    private StorageService storageService;
    @Autowired
    private DicBusinessItemDao dicBusinessItemDao;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private CostRecordService costService;
    @Autowired
    private StockRecordService stockRecordService;
    @Autowired
    private MailSenderService mailSenderService;
    @Value("${gbc.template.localPath}")
    private String templateLocalPath;
    @Autowired
    private DicBusinessItemService dicBusinessItemService;

    @Override
    public PageResult getListPage(Map<String, String> map) {
        QueryWrapper<ReplacementDo> wrapper = queryBuild(map);
        IPage<ReplacementDo> page = pageInit(map);
        page = this.page(page, wrapper);
        List<ReplacementPageRes> resList = handlerListAfter(page.getRecords());
        PageResult result = new PageResult(resList, (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        result.setMapInfo(census(map));
        return result;
    }

    //数据统计
    private Map census(Map<String, String> queryMap) {
        List<Map> result = new ArrayList<>();
        Map mapTotal = new HashMap();
        queryMap.put("status", "");
        List<ReplacementDo> list = dao.selectList(queryBuild(queryMap));
        mapTotal.put("count", list.size());
        mapTotal.put("name", "全部");
        mapTotal.put("id", null);
        result.add(mapTotal);

        Map<Integer, List<ReplacementDo>> listMap = list.stream().collect(Collectors.groupingBy(ReplacementDo::getStatus));

        LambdaQueryWrapper<DicBusinessItemDo> businessItemDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        businessItemDoLambdaQueryWrapper.eq(DicBusinessItemDo::getDicBusinessId, DicBusinessConstant.outPutStatus);
        List<DicBusinessItemDo> businessItemDoList = dicBusinessItemDao.selectList(businessItemDoLambdaQueryWrapper);
        if (!CollectionUtils.isEmpty(businessItemDoList)) {
            for (DicBusinessItemDo itemDo : businessItemDoList) {
                if (itemDo.getId() >= 21 || itemDo.getId() == 17) {
                    continue;
                }
                Integer status = null;
                switch (Long.toString(itemDo.getId())) {
                    case "18":
                        status = 0;
                        break;
                    case "19":
                        status = 1;
                        break;
                    case "20":
                        status = 2;
                        break;
                    default:
                        status = null;
                }
                Map map = new HashMap();
                if (status != null && listMap.get(status) != null) {
                    map.put("count", listMap.get(status).size());
                } else {
                    map.put("count", 0);
                }
                map.put("name", StringsUtil.createI18Message(itemDo.getDicItemValue()));
                map.put("id", status);
                result.add(map);
            }
        }
        Map map = new HashMap();
        map.put("census", result);
        return map;

    }

    private QueryWrapper<ReplacementDo> queryBuild(Map<String, String> map) {
        QueryWrapper<ReplacementDo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(map.get("keyword"))) {
            String keyword = map.get("keyword").replaceAll(" ", "%")
                    .replaceAll("　", "%")
                    .replaceAll("-", "%");
            wrapper.and(new Consumer<QueryWrapper<ReplacementDo>>() {
                @Override
                public void accept(QueryWrapper<ReplacementDo> replacementDoQueryWrapper) {
                    replacementDoQueryWrapper.like("output_order_no", keyword)
                            .or().like("order_no", keyword)
                            .or().like("output_commodity_sku", keyword)
                            .or().like("commodity_sku", keyword)
                            .or().like("output_receiver_name", keyword)
                            .or().like("track_number", keyword)
                            .or().like("product_name", keyword);
                }
            });
        }
        if (StringUtils.isNotBlank(map.get("orderNo"))) {
            wrapper.eq("order_no", map.get("orderNo"));
        }
        if (StringUtils.isNotBlank(map.get("outputShopId"))) {
            wrapper.eq("output_shop_id", map.get("outputShopId"));
        }
        if (StringUtils.isNotBlank(map.get("outputStorageId"))) {
            wrapper.eq("output_storage_id", Integer.parseInt(map.get("outputStorageId")));
        }
        if (StringUtils.isNotBlank(map.get("status"))) {
            wrapper.eq("status", Integer.parseInt(map.get("status")));
        }
        if (StringUtils.isNotBlank(map.get("startDate"))) {
            wrapper.ge("create_time", map.get("startDate"));
        }
        if (StringUtils.isNotBlank(map.get("companyId"))) {
            wrapper.eq("output_company_id", map.get("companyId"));
        }
        if (StringUtils.isNotBlank(map.get("endDate"))) {
            wrapper.le("create_time", map.get("endDate"));
        }
        wrapper.orderByDesc("id");
        return wrapper;
    }

    private IPage<ReplacementDo> pageInit(Map<String, String> map) {
        IPage<ReplacementDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    //查询分页列表之后对列表数据的处理
    private List<ReplacementPageRes> handlerListAfter(List<ReplacementDo> list) {
        List<ReplacementPageRes> result = new ArrayList<>();
        if (list.size() > 0) {
            for (ReplacementDo replacementDo : list) {
                ReplacementPageRes replacementPageRes = new ReplacementPageRes();
                replacementPageRes.setCod(replacementDo.getCod());
                BeanUtils.copyProperties(replacementDo, replacementPageRes);
                replacementPageRes.setStorageName(storageDao.selectById(replacementDo.getOutputStorageId()).getStorageName());
                switch (replacementPageRes.getStatus()) {
                    case 1:
                        replacementPageRes.setStatusName("已打单");
                        break;
                    case 2:
                        replacementPageRes.setStatusName("已发货");
                        break;
                    default:
                        replacementPageRes.setStatusName("已审核");
                        break;
                }
                if (replacementDo.getFileId() != -1L) {
                    replacementPageRes.setUrl(fileService.getFilePath(replacementDo.getFileId()));
                }
                CompanyDo companyDo = mCompanyDao.selectById(replacementDo.getOutputCompanyId());
                if (companyDo != null) {
                    replacementPageRes.setCompanyCode(companyDo.getCompanyCode());
                }
                DicBusinessItemDo dicBusinessItemDo = dicBusinessItemDao.selectById(replacementDo.getTrackId());
                if (dicBusinessItemDo != null) {
                    replacementPageRes.setTrackName(dicBusinessItemDo.getDicItemValue());
                }
                replacementPageRes.setSendDate(TimeUtils.formatDate(replacementDo.getCreateTime()));
                result.add(replacementPageRes);
            }
        }
        return result;
    }

    @Override
    public SingleResult updateR(Long currentUserId, ReplacementUpdateReq replacementUpdateReq) {
        ReplacementDo replacementDo = dao.selectById(replacementUpdateReq.getReplacementAddInitTwoReq().getId());
        if (!replacementDo.getStatus().equals(0)) {
            throw new BizException(SysConstant.Replace_UpdateR_Error);
        }
        long fileId = replacementDo.getFileId();
        replacementDo.setOutputOrderId(replacementUpdateReq.getReplacementAddInitReq().getId());
        replacementDo.setOutputOrderNo(replacementUpdateReq.getReplacementAddInitReq().getOrderNo());
        replacementDo.setOutputArea(replacementUpdateReq.getReplacementAddInitReq().getArea());
        replacementDo.setOutputReceiverName(replacementUpdateReq.getReplacementAddInitReq().getReceiverName());
        replacementDo.setOutputTelPhone(replacementUpdateReq.getReplacementAddInitReq().getTelPhone());
        replacementDo.setOutputAddress(replacementUpdateReq.getReplacementAddInitReq().getAddress());
        replacementDo.setOutputPostCode(replacementUpdateReq.getReplacementAddInitReq().getPostCode());
        replacementDo.setOutputCommoditySku(replacementUpdateReq.getReplacementAddInitReq().getCommoditySku());
        BeanUtils.copyProperties(replacementUpdateReq.getReplacementAddInitTwoReq(), replacementDo);
        BeanUtils.copyProperties(replacementUpdateReq.getReplacementAddInitThreeReq(), replacementDo);
        replacementDo.setUpdateTime(new Date());
        replacementDo.setUpdateBy(currentUserId);
        //图片是否要修改
        if (fileId != replacementUpdateReq.getReplacementAddInitTwoReq().getFileId()) {
            fileService.deleteFile(fileId);
            fileService.uploadFile2(replacementUpdateReq.getReplacementAddInitTwoReq().getFileId(), fileId);
        }
        dao.updateById(replacementDo);
        return SingleResult.success();
    }

    //删除
    @Override
    public SingleResult delete(Long currentUserId, Long id) {
        ReplacementDo replacementDo = dao.selectById(id);
        if (replacementDo == null) {
            throw new BizException(SysConstant.Replace_Delete_NotExist);
        }
        // 0是已下单 但未有其他处理
        if (!replacementDo.getStatus().equals(0)) {
            throw new BizException(SysConstant.Replace_Delete_Error);
        }
        fileService.deleteFile(replacementDo.getFileId());
        replacementDo.setDeleteBy(currentUserId);
        replacementDo.setDeleteTime(new Date());
        dao.deleteById(id);
        return SingleResult.success();
    }

    //将主表中的某些信息带过来
    @Override
    public SingleResult addInit(Long outputId) {
        //新增加一个无关配件
        if (outputId.equals(-1L)) {
            return SingleResult.success();
        }
        Map<String, Object> map = new HashMap<>();
        OrderOutputDo orderOutputDo = orderOutputDao.selectById(outputId);
        if (orderOutputDo == null) {
            throw new BizException(SysConstant.Order_NotExist1);
        }
        ReplacementAddInitReq replacementAddInitReq = new ReplacementAddInitReq();
        BeanUtils.copyProperties(orderOutputDo, replacementAddInitReq);
        //对于CommoditySku 为空进行处理  补发表中需要存储
        if (StringUtils.isBlank(orderOutputDo.getCommoditySku())) {
            QueryWrapper wrapper1 = new QueryWrapper();
            wrapper1.eq("order_id", orderOutputDo.getId());
            List<OrderOutputProductDo> productList = productDao.selectList(wrapper1);
            StringBuilder sb = new StringBuilder();
            for (OrderOutputProductDo productDo : productList) {
                if (sb.length() > 0) {
                    sb.append(",");
                }
                sb.append(productInfoDao.selectById(productDo.getProductId()).getCommoditySku());
            }
            replacementAddInitReq.setCommoditySku(sb.toString());
        }
        map.put("fatherInformation", replacementAddInitReq);
        //前端无需显示的参数
        ReplacementAddInitThreeReq replacementAddInitThreeReq = new ReplacementAddInitThreeReq();
        replacementAddInitThreeReq.setOutputCompanyId(orderOutputDo.getCompanyId());
        replacementAddInitThreeReq.setOutputShopId(orderOutputDo.getShopId());
        replacementAddInitThreeReq.setOutputStorageId(orderOutputDo.getStorageId());
//        StorageDo storageDo = storageDao.selectById(orderOutputDo.getStorageId());
        replacementAddInitThreeReq.setOutputPostCode(orderOutputDo.getPostCode());
        map.put("remainingInformation", replacementAddInitThreeReq);
        //补发信息  可能不存在信息(遍历出来不存在就不显示)  可能多个
        LambdaQueryWrapper<ReplacementDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ReplacementDo::getOutputOrderId, outputId);
        List<ReplacementDo> replacementDos = dao.selectList(wrapper);
        //为空跳过
        if (replacementDos.size() < 1) {
            return SingleResult.success(map);
        }
        List<ReplacementAddInitTwoReq> list = new ArrayList();
        for (ReplacementDo replacementDo : replacementDos) {
            ReplacementAddInitTwoReq replacementAddInitTwoReq = new ReplacementAddInitTwoReq();
            BeanUtils.copyProperties(replacementDo, replacementAddInitTwoReq);
            //获取图片链接
            replacementAddInitTwoReq.setUrl(fileService.getFilePath(replacementDo.getFileId()));
            list.add(replacementAddInitTwoReq);
            map.put("sonInformation", list);
        }
        //传sku列表
        List<Map> productInfoDos = new ArrayList<>();
        List<ProductInfoDo> productInfoDoList = productInfoDao.selectList(null);
        for (ProductInfoDo productInfoDo : productInfoDoList) {
            Map<String, Object> product = new HashMap<>();
            product.put("id", productInfoDo.getId());
            product.put("value", productInfoDo.getCommoditySku());
            productInfoDos.add(product);
        }
        map.put("productInfoId", productInfoDos);
        return SingleResult.success(map);
    }

    //添加
    @Override
    public SingleResult add(Long currentUserId, ReplacementAddReq addReq, Long companyId) {
        if (addReq.getReplacementAddInitTwoReqList().size() < 1) {
            return SingleResult.success();
        }
        for (ReplacementAddInitTwoReq replacementAddInitTwoReq : addReq.getReplacementAddInitTwoReqList()) {
            ReplacementDo replacementDo = new ReplacementDo();
            replacementDo.setOutputOrderId(addReq.getReplacementAddInitReq().getId());
            replacementDo.setOutputOrderNo(addReq.getReplacementAddInitReq().getOrderNo());
            replacementDo.setOutputArea(addReq.getReplacementAddInitReq().getArea());
            replacementDo.setOutputReceiverName(addReq.getReplacementAddInitReq().getReceiverName());
            replacementDo.setOutputTelPhone(addReq.getReplacementAddInitReq().getTelPhone());
            replacementDo.setOutputAddress(addReq.getReplacementAddInitReq().getAddress());
            replacementDo.setOutputPostCode(addReq.getReplacementAddInitReq().getPostCode());
            replacementDo.setOutputCommoditySku(addReq.getReplacementAddInitReq().getCommoditySku());
            if (replacementAddInitTwoReq.getFileId() == null) {
                replacementAddInitTwoReq.setFileId(-1L);
            }
            if (StringUtils.isNotBlank(addReq.getReplacementAddInitReq().getCod())) {
                int cod = 0;
                try {
                    cod = Integer.parseInt(addReq.getReplacementAddInitReq().getCod());
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
                replacementDo.setCod(cod);
            }
            BeanUtils.copyProperties(replacementAddInitTwoReq, replacementDo);
            BeanUtils.copyProperties(addReq.getReplacementAddInitThreeReq(), replacementDo);
            if (!replacementAddInitTwoReq.getFileId().equals(-1L)) {
                fileService.uploadFile(replacementAddInitTwoReq.getFileId());
            }
            LambdaQueryWrapper<ProductInfoDo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ProductInfoDo::getCommoditySku, replacementDo.getOutputCommoditySku());
            wrapper.eq(ProductInfoDo::getCompanyId, replacementDo.getOutputCompanyId());
            if (replacementDo.getSize() == null || replacementDo.getSize() == 1) {
                replacementDo.setTrackId(8L);
            }
            ProductInfoDo productInfoDo = productInfoDao.selectOne(wrapper);
            if (productInfoDo == null) {
                throw new BizException(SysConstant.Product_NotExist);
            }
            replacementDo.setProductInfoId(productInfoDo.getId());
            replacementDo.setCreateTime(new Date());
            replacementDo.setCreateBy(currentUserId);
            if (replacementDo.getOutputCompanyId() == null) {
                replacementDo.setOutputCompanyId(companyId);
            }
            dao.insert(replacementDo);
            String stringCode = OrderCodeUtil.getOrderReplaceNumber(replacementDo.getId());
            replacementDo.setOrderNo(stringCode);
            if (addReq.getReplacementAddInitReq().getId() == null || addReq.getReplacementAddInitReq().getId() == 0) {
                replacementDo.setOutputOrderId(replacementDo.getId());
            }
            updateById(replacementDo);
        }
        return SingleResult.success();
    }

    @Override
    public SingleResult pageInit(Long companyId, Long currentUserId) {
        Map map = new HashMap();
        Map storageMap = new HashMap();
        storageMap.put("countryType", "1");
        map.put("storageList", storageService.getList(storageMap));
        List<Long> ids = new ArrayList<>();
        map.put("trackList", dicBusinessItemService.getDicItemList(DicBusinessConstant.trackCompany));
//        List<Map> shopList = companyService.getInitList(companyId);
//        map.put("shopList", shopList);
        //公司相关信息
//        List<CompanyDo> companyDos = mCompanyDao.selectList(null);
//        List<Map> companyList = new ArrayList<>();
//        for (CompanyDo companyDo : companyDos) {
//            Map<String, Object> companyMap = new HashMap<>();
//            companyMap.put("id", companyDo.getId());
//            companyMap.put("value", companyDo.getCompanyCode());
//            companyList.add(companyMap);
//        }
//        map.put("company", companyList);
        map.put("companyTree", companyService.tree());
        map.put("status", getStatusMap());
        return SingleResult.success(map);
    }

    private List<IdAndNameEntity> getStatusMap() {
        List<IdAndNameEntity> map = new ArrayList<>();
        map.add(new IdAndNameEntity(0, "已审核"));
        map.add(new IdAndNameEntity(1, "已打单"));
        map.add(new IdAndNameEntity(2, "已发货"));
        return map;
    }


    //得到当前公司的sku List
    @Override
    public SingleResult getSkuList(Long companyId, Long currentUserId) {
        Map<String, List> map = new HashMap();
        LambdaQueryWrapper<ProductInfoDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductInfoDo::getCompanyId, companyId);
        List<ProductInfoDo> productInfoDos = productInfoDao.selectList(wrapper);
        List<Map> mapList = new ArrayList<>();
        for (ProductInfoDo productInfoDo : productInfoDos) {
            Map<String, Object> productMap = new HashMap<>();
            productMap.put("id", productInfoDo.getId());
            productMap.put("value", productInfoDo.getCommoditySku());
            mapList.add(productMap);
        }
        map.put("sku", mapList);
        return SingleResult.success(map);
    }

    //打印信息
    @Override
    public void exportMessage(ReplacementExportReq req, HttpServletResponse response) {
        //判空
        if (req.getIds().size() < 1) {
            throw new BizException(SysConstant.Replace_Choose_Data);
        }
        //找出对应信息
        List<ReplacementDo> replacementDoList = dao.selectBatchIds(req.getIds());
        if (replacementDoList.size() < 1) {
            throw new BizException(SysConstant.Replace_Export_NoProduct);
        }
        //数据迁移
        List<ReplacementExcel> list = new ArrayList<>();
        for (ReplacementDo replacementDo : replacementDoList) {
            ReplacementExcel replacementExcel = new ReplacementExcel();
            BeanUtils.copyProperties(replacementDo, replacementExcel);
            list.add(replacementExcel);
        }
        //打印
        try {
            ExcelUtils.exportExcel(list, ReplacementExcel.class, "配件信息", new ExportParams(), response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    public Map dealwithTrackNumberExcel(MultipartFile file, Long userid) {
        List<OrderOutputTrackNumberExcelImport> excelImportList = new ArrayList<>();
        if (StringUtils.isEmpty(file.getName())) {
            throw new BizException(SysConstant.File_Name_Null);
        }
        /* if (storageId == 0) throw new BizException("请选择发货仓库");*/
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        if (!GlobalConstants.IMG_TYPE_XLS.equals(suffix.toUpperCase()) &&
                !GlobalConstants.IMG_TYPE_XLSX.equals(suffix.toUpperCase())) {
            throw new BizException(SysConstant.File_Form_Incorrect);
        }
        try {
            excelImportList = ExcelUtils.importExcel(file, 0, 0, OrderOutputTrackNumberExcelImport.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (excelImportList == null || excelImportList.size() == 0) {
            throw new BizException(SysConstant.File_FormWork_Incorrect);
        }

        return dealwithExcelData(excelImportList, userid);
    }

    private Map dealwithExcelData(List<OrderOutputTrackNumberExcelImport> excelImportList, Long userid) {
        Map map = new HashMap();
        int totalCount = 0;
        List<String> orderNumbers = new ArrayList<>();
        for (int i = 0; i < excelImportList.size(); i++) {
            OrderOutputTrackNumberExcelImport excelData = excelImportList.get(i);
            if (excelData == null) continue;
            if (excelData.getOrderOTNumber() == null) continue;
            excelData.setOrderOTNumber(excelData.getOrderOTNumber().trim());
            if (excelData.getTrackNumber() == null) {
                orderNumbers.add(excelData.getOrderOTNumber() + "运单号为空");
                continue;
            }
            excelData.setTrackNumber(excelData.getTrackNumber().trim());
            LambdaQueryWrapper<ReplacementDo> wrapper = new LambdaQueryWrapper();
            wrapper.eq(ReplacementDo::getOrderNo, excelData.getOrderOTNumber());
            ReplacementDo outputDo = dao.selectOne(wrapper);
            if (outputDo == null) {
                wrapper = new LambdaQueryWrapper();
                wrapper.or(orderWrapper -> {
                    orderWrapper.eq(ReplacementDo::getOrderNo, excelData.getOrderOTNumber())
                            .or().like(ReplacementDo::getOutputReceiverName, excelData.getOrderOTNumber().replaceAll(" ",
                                    "%").replaceAll("　", "%"));
                });
                wrapper.and(orderQueryWrapper -> {
                    orderQueryWrapper.eq(ReplacementDo::getStatus, 1).or()
                            .eq(ReplacementDo::getStatus, 0);
                });
                wrapper.orderByAsc(ReplacementDo::getCreateTime);
                wrapper.last("limit 1");
                outputDo = dao.selectOne(wrapper);
            }
            if (outputDo != null && !excelData.getTrackNumber().equals(outputDo.getTrackNumber())) {
                outputDo.setTrackNumber(excelData.getTrackNumber());
                outputDo.setUpdateBy(userid);
                outputDo.setUpdateTime(new Date());
                saveOrUpdate(outputDo);
                if (outputDo.getStatus() < 2) {
                    dealwithOrderSendOut(outputDo, outputDo.getTrackId(), excelData.getTrackNumber(), userid);
                }
                totalCount++;
//                if (outputDo.getStatus() == DicBusinessItemConstant.orderCutOff) {
//                    orderNumbers.add(excelData.getOrderOTNumber() + "顾客申请截单，请追回订单！");
//                }
            } else {
                orderNumbers.add(excelData.getOrderOTNumber() + "订单不存在或已经上传运单号");
            }
        }
//        if (orderNumbers.size() > 0)
//            autoUploadExpressNumber(orderNumbers);
//        executeTaskT(excelImportList);Amz
        map.put("count", totalCount);
        map.put("error", orderNumbers);
        return map;
    }

    @Override
    public void dealwithOrderSendOut(ReplacementDo outputDo, Long trackId, String trackNumber, Long userid) {
        LambdaQueryWrapper<ReplacementDo> wrapper = new LambdaQueryWrapper();
        wrapper.eq(ReplacementDo::getOutputOrderNo, outputDo.getOutputOrderNo());
        wrapper.eq(ReplacementDo::getOutputReceiverName, outputDo.getOutputReceiverName());
        wrapper.eq(ReplacementDo::getStatus, 1);
        wrapper.ne(ReplacementDo::getId, outputDo.getId());
        List<ReplacementDo> replacementDoList = dao.selectList(wrapper);
        if (replacementDoList.size() > 0) {
            replacementDoList.stream().forEach(replacementDo -> {
                replacementDo.setStatus(2);
                if (trackId != null)
                    replacementDo.setTrackId(trackId);
                replacementDo.setTrackNumber(trackNumber);
                replacementDo.setUpdateTime(new Date());
                replacementDo.setUpdateBy(userid);
                replacementDo.setDealBy(userid);
                replacementDo.setDealTime(new Date());
                //todo 扣库存
                if (replacementDo.getIsDevanning() == SysConstant.DELETE_FLAG_TRUE) {
                    stockRecordService.turn2BadStock(replacementDo.getOutputCommoditySku(),
                            replacementDo.getOutputShopId(), replacementDo.getOutputStorageId(), replacementDo.getNumber(),
                            replacementDo.getOrderNo(), userid);
                }
                updateById(replacementDo);
            });
        }
        outputDo.setStatus(2);
        if (trackId != null)
            outputDo.setTrackId(trackId);
        outputDo.setTrackNumber(trackNumber);
        outputDo.setUpdateTime(new Date());
        outputDo.setUpdateBy(userid);
        outputDo.setDealBy(userid);
        outputDo.setDealTime(new Date());

        //todo 收费
        double costAmount = 0;
        if (outputDo.getSize() == SysConstant.DELETE_FLAG_FALSE) {
            costAmount = 1000;
        } else {
            costAmount = 2000;
        }
        costService.add(0, outputDo.getOrderNo() + "发配件", costAmount, outputDo.getOutputShopId(), outputDo.getOutputCompanyId(), outputDo.getId());
        //todo 扣库存
        if (outputDo.getIsDevanning() == SysConstant.DELETE_FLAG_TRUE) {
            stockRecordService.turn2BadStock(outputDo.getOutputCommoditySku(),
                    outputDo.getOutputShopId(), outputDo.getOutputStorageId(), outputDo.getNumber(), outputDo.getOrderNo(), userid);
        }
        updateById(outputDo);
    }

    //发送邮件
    @Override
    public SingleResult sendEmail(ReplacementSendEmailReq replacementSendEmail, Long currentUserId) throws Exception {
        if (replacementSendEmail.getIds().size() < 1) {
            throw new BizException(SysConstant.Replace_Choose_SendTo);
        }
        List<ReplacementDo> replacementDos = new ArrayList<>();
        //可能会出现选择发送的数据  涉及到多个不同的仓库  根据不同的仓库就行分组
        for (Long id : replacementSendEmail.getIds()) {
            replacementDos.add(dao.selectById(id));
        }
        //此key就是storageid
        Map<Long, List<ReplacementDo>> collect = replacementDos.stream().collect(Collectors.groupingBy(ReplacementDo::getOutputStorageId));
        //利用Java发送邮件
        Session session = mailSenderService.initMailSession();
        Transport transport = mailSenderService.initMailTransport(session);
        //设置时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
        String date = simpleDateFormat.format(new Date());
        for (Long aLong : collect.keySet()) {
            //对不同的仓库进行处理
            List<ReplacementDo> replacementDoList = collect.get(aLong);
            List<MailReplacementTemplateEntity> mailReplacementReqs = new ArrayList<>();
            for (ReplacementDo replacementDo : replacementDoList) {
                MailReplacementTemplateEntity mailReplacementReq = new MailReplacementTemplateEntity();
                BeanUtils.copyProperties(replacementDo, mailReplacementReq);
                //判断是否有图 -1为没有图
                mailReplacementReq.setFilePath(fileService.getFilePath(replacementDo.getFileId()));
                mailReplacementReqs.add(mailReplacementReq);
            }
            //获取路径
            String path = ResourceUtils.getFile(templateLocalPath + "replacement_confirm.ftl").getPath();
            String message = FreeMarkerUtils.sendStorageReplaceMail(mailReplacementReqs, getStorageMap(aLong.intValue()), path);
            switch (aLong.intValue()) {
//                ksw
                case 1:
                    //将数据写入模板 再将数据写入邮件中
                    mailSenderService.sendEmail(session, transport, "筋斗雲(株)" + date + "パーツ出荷依頼のお知らせ", message,
                            "m_odo@shinkashiwa-soko.co.jp", "r_tomizawa@shinkashiwa-soko.co.jp,izumi-2@shinkashiwa-soko.co.jp," +
                                    "m_kaneko@shinkashiwa-soko.co.jp,y_katsumata@shinkashiwa-soko.co.jp,service1@cloudkinto.com," +
                                    "hujingwen@sanchoum.com,rbzyy@sanchoum.com");
                    break;
                //thk
                case 2:
                    mailSenderService.sendEmail(session, transport, "筋斗雲(株)" + date + "パーツ出荷依頼のお知らせ", message,
                            "yamamoto@think21.co.jp", "service1@cloudkinto.com,hujingwen@sanchoum.com,rbzyy@sanchoum.com");
                    break;
                //skl 5
                case 5:
                    mailSenderService.sendEmail(session, transport, "筋斗雲(株)" + date + "パーツ出荷依頼のお知らせ", message,
                            "d-gotou@sklg.co.jp", "t-tsuyutani@sklg.co.jp,service1@cloudkinto.com,hujingwen@sanchoum.com,rbzyy@sanchoum.com");
                    break;
//                default:
//                    mailSenderService.sendEmail(session, transport, "筋斗雲(株)" + date + "パーツ出荷依頼のお知らせ", message,
//                "service@cloudkinto.com", "2399653280@qq.com,hujingwen@sanchoum.com,rbzyy@sanchoum.com");
//                            "service@cloudkinto.com", "2399653280@qq.com");
//                break;
            }
        }
        updateOrderWaitSend(replacementSendEmail.getIds(), currentUserId);
        return SingleResult.success();
    }

    @Override
    public SingleResult updateOrderWaitSend(List<Long> ids, Long currentUserId) {
        List<ReplacementDo> orderOutputDoList;
        if (ids != null && ids.size() > 0) {
            orderOutputDoList = this.baseMapper.selectBatchIds(ids);
        } else {
//            orderOutputDoList = this.baseMapper.selectList1(map);
//            response.setStatus(500);
//            return null;
            throw new BizException(SysConstant.Pls_Choose_Order);
        }
//        List<Long> orderIds = new ArrayList<>();
        orderOutputDoList = orderOutputDoList.stream()
                .filter(orderOutputDo -> orderOutputDo.getStatus() == 0)
                .map(orderOutputDo -> {
                    orderOutputDo.setStatus(1);
                    if (orderOutputDo.getTrackId() == null)
                        orderOutputDo.setTrackId(DicBusinessItemConstant.sagawaExpress);
                    orderOutputDo.setUpdateTime(new Date());
                    orderOutputDo.setUpdateBy(currentUserId);
                    return orderOutputDo;
                }).collect(Collectors.toList());
        if (orderOutputDoList.size() < 1) return SingleResult.success();
        boolean b = updateBatchById(orderOutputDoList);
        return b ? SingleResult.success() : SingleResult.failure("更新失败，请联系管理员");
    }

    private Map<String, String> getStorageMap(int intValue) {
        Map<String, String> map = new HashMap<>();
        switch (intValue) {
            //ksw
            case 1:
                //将数据写入模板 再将数据写入邮件中
                map.put("storageName", "新柏倉庫株式会社");
                map.put("managerName", "尾洞 様");
                break;
            //thk
            case 2:
                map.put("storageName", "シンク株式会社");
                map.put("managerName", "山本 様");
                break;
            //skl 5
            case 5:
                map.put("storageName", "エスケーロジ株式会社");
                map.put("managerName", "後藤 様");
                break;
            default:
                map.put("storageName", "筋斗雲株式会社");
                map.put("managerName", "胡 様");
                break;
        }
        return map;
    }

    @Override
    public SingleResult checkMessage(ReplacementSendEmailReq ids) {
        List<Long> newList = new ArrayList();
        List<ReplacementDo> replacementDoList = new ArrayList();
        //找到所有的对象值
        List<ReplacementDo> replacementDos = dao.selectBatchIds(ids.getIds());
        //过滤掉没有outputOrderId的数据
        List<ReplacementDo> collect =
                replacementDos.stream().filter(replacementDo -> replacementDo.getOutputOrderId() != null)
                        .collect(Collectors.toList());
        //得到新的outputOrderId list
        for (ReplacementDo replacementDo : collect) {
            newList.add(replacementDo.getOutputOrderId());
        }
        for (Long orderId : newList) {
            //筛选出审核状态下的数据
            LambdaQueryWrapper<ReplacementDo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ReplacementDo::getOutputOrderId, orderId)
                    .eq(ReplacementDo::getStatus, 0);
            List<ReplacementDo> replacementDos1 = dao.selectList(wrapper);
            //对比得到不同数据
            List<ReplacementDo> diffList = Stream.of(replacementDoList, replacementDos1)
                    .flatMap(Collection::stream).distinct().collect(Collectors.toList());
            //数据迁移
            replacementDoList.addAll(diffList);
        }
        //数据对比如果全部包含则直接返回
        if (replacementDos.containsAll(replacementDoList)) {
            return SingleResult.success();
        }
        //不包含全部则需要将不包含的数据放入
        List<ReplacementDo> compareList = new ArrayList<>();
        if (replacementDoList.size() > replacementDos.size()) {
            for (ReplacementDo replacementDo : replacementDoList) {
                if (!replacementDos.contains(replacementDo)) {
                    compareList.add(replacementDo);
                }
            }
        } else {
            for (ReplacementDo replacementDo : replacementDos) {
                if (!replacementDoList.contains(replacementDo)) {
                    compareList.add(replacementDo);
                }
            }
        }
        /*//过滤OutputOrderId为空的
        List<ReplacementDo> collectList =
                replacementDos.stream()
                        .filter(replacementDo -> replacementDo.getOutputOrderId() != null)
                        .collect(Collectors.toList());
        //根据对象中的某一属性去重 set
        TreeSet<ReplacementDo> treeSet
                = collectList.stream().collect(Collectors.toCollection
                (() -> new TreeSet<>(Comparator.comparing(ReplacementDo::getOutputOrderId))));
        //根据去重的orderId 找出数据
        List<ReplacementCompareRes> resultList = new ArrayList();
        for (ReplacementDo replacementDo : treeSet) {
            LambdaQueryWrapper<ReplacementDo>  wrapper=new LambdaQueryWrapper<>();
            wrapper.eq(ReplacementDo::getOutputOrderId,replacementDo.getOutputOrderId());
            List<ReplacementDo> replacementList = dao.selectList(wrapper);
            for (ReplacementDo replacement : replacementList) {
                ReplacementCompareRes replacementCompareRes = new ReplacementCompareRes();
                BeanUtils.copyProperties(replacement,replacementCompareRes);
                resultList.add(replacementCompareRes);
            }
        }
        //得到需要返回的数据进行比对
        List<Long> replacementCompareIds=new ArrayList<>();
        for (ReplacementCompareRes replacementCompareRes : resultList) {
            replacementCompareIds.add(replacementCompareRes.getId());
        }*/
        return SingleResult.success(compareList);
    }


    @Override
    public SingleResult truck(ReplacementTruckReq replacementTruckReq, Long currentUserId) {
        ReplacementDo replacementDo = dao.selectById(replacementTruckReq.getId());
        dealwithOrderSendOut(replacementDo, replacementTruckReq.getTrackId(), replacementTruckReq.getTrackNumber(), currentUserId);
        return SingleResult.success("修改成功");
    }


    //打印补发拣货单
    @Override
    public void exportExcel(List<Long> ids, HttpServletResponse response) {
        List<ReplacementDo> orderOutputDoList;
        if (ids != null && ids.size() > 0) {
            orderOutputDoList = this.baseMapper.selectBatchIds(ids);
        } else {
//            response.setStatus(500);
//            return null;
//            orderOutputDoList = this.baseMapper.selectList1(map);
            throw new BizException(SysConstant.Pls_Choose_Order);
        }
        List<ReplacementPickUpExcel> exportVoList = new ArrayList<>();

        orderOutputDoList.stream()
                .sorted(new Comparator<ReplacementDo>() {
                    @Override
                    public int compare(ReplacementDo o1, ReplacementDo o2) {
                        if (o1.getCommoditySku() == null || o2.getCommoditySku() == null) return 1;
                        return o1.getCommoditySku().compareTo(o2.getCommoditySku());
                    }
                })
                .forEach(replacementDo -> {
                    ReplacementPickUpExcel replacementExcel = new ReplacementPickUpExcel();
                    CompanyDo companyDo = companyService.getById(replacementDo.getOutputCompanyId());
                    if (StringUtils.isNotBlank(companyDo.getCompanyCode())) {
                        replacementExcel.setCompanyCode(companyDo.getCompanyCode());
                    }
                    BeanUtils.copyProperties(replacementDo, replacementExcel);
                    replacementExcel.setPicture(fileService.getFilePath(replacementDo.getFileId()));
                    exportVoList.add(replacementExcel);
                });
        //打印
        ExportParams exportParams = new ExportParams();
        exportParams.setTitle(String.format("%s 配件拣货单", TimeUtils.getCurrentDateFormat("MM/dd")));
        try {
//            ExcelUtils.downLoadExcel(TimeUtils.getCurrentDateFormat() + "补发拣货单.xls", response, workbook);
            ExcelUtils.exportExcel(exportVoList, ReplacementPickUpExcel.class, TimeUtils.getCurrentDateFormat() + "配件拣货单.xls", exportParams, response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void exportTrackExpress(Map<String, String> map, List<Long> ids, HttpServletResponse response) {
        //去重
        List<Long> collect = ids.stream().distinct().collect(Collectors.toList());
        List<ReplacementDo> orderOutputDoList;
        if (collect != null && collect.size() > 0) {
            orderOutputDoList = this.baseMapper.selectBatchIds(collect);
        } else {
            throw new BizException(SysConstant.Pls_Choose_Order);
        }
        long[] lastOrderId = new long[1];
        List<OrderOutputSagawaExportVo> sagawaExportVoList = new ArrayList<>();
        orderOutputDoList.stream()
                .sorted(Comparator.comparing(ReplacementDo::getOutputOrderId))
                .forEach(orderOutputDo -> {
                    if (lastOrderId[0] == orderOutputDo.getOutputOrderId()) {
                        OrderOutputSagawaExportVo orderOutputSagawaExportVo = sagawaExportVoList.get(sagawaExportVoList.size() - 1);
                        if (StringUtils.isBlank(orderOutputSagawaExportVo.getCommoditySku())) {
                            orderOutputSagawaExportVo.setCommoditySku(orderOutputDo.getCommoditySku());
                        } else if (StringUtils.isBlank(orderOutputSagawaExportVo.getStorageSku())) {
                            orderOutputSagawaExportVo.setCommoditySku1(orderOutputDo.getCommoditySku());
                        } else if (StringUtils.isBlank(orderOutputSagawaExportVo.getStorageSku())) {
                            orderOutputSagawaExportVo.setStorageSku(orderOutputDo.getCommoditySku());
                        } else if (StringUtils.isBlank(orderOutputSagawaExportVo.getStorageSku1())) {
                            orderOutputSagawaExportVo.setStorageSku1(orderOutputDo.getCommoditySku());
                        }

                    } else {
                        sagawaExportVoList.add(buidSagawaExportData(orderOutputDo));
                    }
                    lastOrderId[0] = orderOutputDo.getOutputOrderId();
                });
        CsvExportParams exportParams = new CsvExportParams();
        exportParams.setCreateHeadRows(true);
        exportParams.setEncoding("Shift-JIS");
        CsvUtils.exportCsv(exportParams, OrderOutputSagawaExportVo.class, sagawaExportVoList,
                TimeUtils.getCurrentDateFormat() + "Sagawa.csv", response);
//                        ExcelUtils.exportExcel(sagawaExportVoList, OrderOutputSagawaExportVo.class, TimeUtils.getCurrentDateFormat() + "Sagawa出荷依頼.xls", new ExportParams(), response);
    }


    private OrderOutputSagawaExportVo buidSagawaExportData(ReplacementDo orderOutputDo) {
        OrderOutputSagawaExportVo exportVo = new OrderOutputSagawaExportVo();
        if (orderOutputDo.getOutputStorageId() == 1 ||
                orderOutputDo.getOutputStorageId() == 10 ||
                orderOutputDo.getOutputStorageId() == 11) {
            exportVo.setE3("146671890039");
            exportVo.setE5("0471-36-1830");
            exportVo.setE6("0471-36-1830");
            exportVo.setE7("278-0002");
            exportVo.setE8("千葉県野田市木野崎字");
            exportVo.setE9("鹿野1788番地２-1");
        } else if (orderOutputDo.getOutputStorageId() == 12) {
            exportVo.setE3("");
            exportVo.setE5("0471361830");
            exportVo.setE6("0471361830");
            exportVo.setE7("6500011");
            exportVo.setE8("兵庫県神戸市中央区下山手通２-");
            exportVo.setE9("１３-３建創ビル８階２０号室");
            exportVo.setE10("EC通販物流センター（関西）");
        }if (orderOutputDo.getOutputShopId().intValue() == 1) {
            exportVo.setE10("MWPO（モロ）株式会社(AMAZON)");
        } else if (orderOutputDo.getOutputShopId().intValue() == 2) {
            exportVo.setE10("SCM株式会社(AMAZON)");
        } else if (orderOutputDo.getOutputShopId().intValue() == 3) {
            exportVo.setE10("チチロバ（TITIROBA）楽天市場店");
        } else if (orderOutputDo.getOutputShopId().intValue() == 4) {
            exportVo.setE10("MWPO（モロ）株式会社(楽天)");
        } else if (orderOutputDo.getOutputShopId().intValue() == 6) {
            exportVo.setE10("MWPO（モロ）株式会社公式サイト");
        } else if (orderOutputDo.getOutputShopId().intValue() == 33) {
            exportVo.setE10("EOWO直営店(AMAZON)");
        } else if (orderOutputDo.getOutputShopId().intValue() == 221) {
            exportVo.setE10("lifesia (AMAZON)");
        } else if (orderOutputDo.getOutputShopId().intValue() == 301) {
            exportVo.setE10("楽天titilife");
        } else if (orderOutputDo.getOutputCompanyId() == 84) {
            exportVo.setE10("チチロバ（TITIROBA）楽天市場店");
        } else if (orderOutputDo.getOutputCompanyId().intValue() == 201) {
            exportVo.setE10("AfterShokz Official Store");
        } else if (orderOutputDo.getOutputCompanyId() == 80) {
            exportVo.setE10("NIXGIRE LIMITED");
        } else if (orderOutputDo.getOutputCompanyId().intValue() == 323) {
            exportVo.setE10("MamimamiHome");
        } else if (orderOutputDo.getOutputCompanyId().intValue() == 263) {
            exportVo.setE10("UWANT");
        } else if (orderOutputDo.getOutputCompanyId().intValue() == 218) {
            exportVo.setE10("CXWXC");
        } else if (orderOutputDo.getOutputCompanyId().intValue() == 300) {
            exportVo.setE10("Morus(乾燥機)");
            exportVo.setE6("050-5534-9451");
        } else if (orderOutputDo.getOutputCompanyId().intValue() == 221) {
            exportVo.setE10("RENOGY JAPAN");
            exportVo.setE6("048-299-9264");
            exportVo.setE7("3330866");
            exportVo.setE8("埼玉県川口市芝1丁目");
            exportVo.setE9("30-61F 柳ビル");
        } else if (orderOutputDo.getOutputCompanyId() == 14) {
            exportVo.setE10("OneTigris Camping");
            exportVo.setE7("1580094");
            exportVo.setE8("東京都世田谷区玉川");
            exportVo.setE9("１-１４-１");
        } else if (orderOutputDo.getOutputShopId().intValue() == 395) {
            exportVo.setE10("楽天市場 Greatstar Official");
            exportVo.setE6("0471-36-1830");
        }
        if (StringUtils.isNotBlank(orderOutputDo.getOutputTelPhone()))
            exportVo.setTelPhone(orderOutputDo.getOutputTelPhone().replaceAll("\\n", ""));
        if (StringUtils.isNotBlank(orderOutputDo.getOutputPostCode()))
            exportVo.setPostCode(orderOutputDo.getOutputPostCode().replaceAll("-", "").replaceAll("\\n", ""));
        orderOutputDo.setOutputAddress(orderOutputDo.getOutputAddress().replaceAll("\\n", ""));
        if (orderOutputDo.getOutputAddress().length() <= 15) {
            exportVo.setAddress1(orderOutputDo.getOutputAddress());
        } else if (orderOutputDo.getOutputAddress().length() > 15 && orderOutputDo.getOutputAddress().length() <= 30) {
            exportVo.setAddress1(orderOutputDo.getOutputAddress().substring(0, 15));
            exportVo.setAddress2(orderOutputDo.getOutputAddress().substring(15));
        } else {
            exportVo.setAddress1(orderOutputDo.getOutputAddress().substring(0, 15));
            exportVo.setAddress2(orderOutputDo.getOutputAddress().substring(15, 30));
            exportVo.setAddress3(orderOutputDo.getOutputAddress().substring(30));
        }
        if (StringUtils.isNotBlank(orderOutputDo.getOutputReceiverName())) {
            orderOutputDo.setOutputReceiverName(orderOutputDo.getOutputReceiverName().replaceAll("\\n", ""));
            if (orderOutputDo.getOutputReceiverName().length() <= 15) {
                exportVo.setReceiverName(orderOutputDo.getOutputReceiverName());
            } else {
                exportVo.setReceiverName(orderOutputDo.getOutputReceiverName().substring(0, 15));
                exportVo.setReceiverName2(orderOutputDo.getOutputReceiverName().substring(15));
            }
        }
//            if (sku.length() > 30) {
//                exportVo.setCommoditySku(sku.substring(0, 20));
//            } else {
        exportVo.setCommoditySku(orderOutputDo.getCommoditySku());
        exportVo.setOrderNumber(orderOutputDo.getOrderNo());
        exportVo.setDeliveryTimeCode("0");
        if (orderOutputDo.getCod() != null && orderOutputDo.getCod() != 0) {
            exportVo.setCod(String.valueOf(orderOutputDo.getCod()));
        }
//            }
//        exportVo.setStorageSku(storageSku.toString());
        exportVo.setCount("1");
//        wrapper = new QueryWrapper();
//        wrapper.eq("package_id", orderInputProductDo.getId());
        return exportVo;

    }


    private OrderOutputYamatoExportVo buildYamatoExportData(ReplacementDo orderOutputDo) {
        OrderOutputYamatoExportVo exportVo = new OrderOutputYamatoExportVo();
        if (orderOutputDo.getOutputShopId().intValue() == 1) {
            exportVo.setE9("MWPO（モロ）株式会社(AMAZON)");
        } else if (orderOutputDo.getOutputShopId().intValue() == 2) {
            exportVo.setE9("SCM株式会社(AMAZON)");
        } else if (orderOutputDo.getOutputShopId().intValue() == 3) {
            exportVo.setE9("PRORS(AMAZON)");
        } else if (orderOutputDo.getOutputShopId().intValue() == 4) {
            exportVo.setE9("MWPO（モロ）株式会社(楽天)");
        } else if (orderOutputDo.getOutputShopId().intValue() == 6) {
            exportVo.setE9("MWPO（モロ）株式会社公式サイト");
        } else if (orderOutputDo.getOutputShopId().intValue() == 33) {
            exportVo.setE9("EOWO直営店(AMAZON)");
        } else if (orderOutputDo.getOutputShopId().intValue() == 221) {
            exportVo.setE9("lifesia (AMAZON)");
        } else if (orderOutputDo.getOutputShopId().intValue() == 301) {
            exportVo.setE9("楽天titilife");
        } else if (orderOutputDo.getOutputCompanyId() == 84) {
            exportVo.setE9("チチロバ楽天市場店");
        } else if (orderOutputDo.getOutputCompanyId() == 201) {
            exportVo.setE9("AfterShokz Official Store");
        } else if (orderOutputDo.getOutputCompanyId() == 80) {
            exportVo.setE9("NIXGIRE LIMITED");
        } else if (orderOutputDo.getOutputCompanyId().intValue() == 263) {
            exportVo.setE9("UWANT");
        } else if (orderOutputDo.getOutputCompanyId().intValue() == 218) {
            exportVo.setE9("CXWXC");
        } else if (orderOutputDo.getOutputCompanyId().intValue() == 323) {
            exportVo.setE9("MamimamiHome");
        } else if (orderOutputDo.getOutputCompanyId() == 14) {
            exportVo.setE9("OneTigris Camping");
            exportVo.setE10("1580094");
            exportVo.setE11("東京都世田谷区玉川１-１４-１");
        } else if (orderOutputDo.getOutputCompanyId().intValue() == 221) {
            exportVo.setE9("RENOGY JAPAN");
            exportVo.setE7("048-299-9264");
            exportVo.setE10("3330866");
            exportVo.setE11("埼玉県川口市芝1丁目30-61F 柳ビル");
        } else if (orderOutputDo.getOutputShopId().intValue() == 395) {
            exportVo.setE9("楽天市場 Greatstar Official");
            exportVo.setE7("0471-36-1830");
        } else if (orderOutputDo.getOutputCompanyId().intValue() == 300) {
            exportVo.setE9("Morus(乾燥機)");
            exportVo.setE7("050-5534-9451");
        } else if (orderOutputDo.getOutputCompanyId().intValue() == 263) {
            exportVo.setE9("UWANT");
        }
        exportVo.setSendDate(TimeUtils.formatDate(new Date(), "yyy/MM/dd"));
        if (StringUtils.isNotBlank(orderOutputDo.getOutputTelPhone()))
            exportVo.setManagerNo(orderOutputDo.getOutputTelPhone().replaceAll("\\+81", ""));
        exportVo.setE2(orderOutputDo.getOutputTelPhone());
        exportVo.setReceiverTelPhone(orderOutputDo.getOutputTelPhone().replaceAll("－", "").replaceAll("-", ""));
        if (StringUtils.isNotBlank(exportVo.getReceiverTelPhone()) && exportVo.getReceiverTelPhone().startsWith("81")) {
            exportVo.setReceiverTelPhone(exportVo.getReceiverTelPhone().replaceFirst("81", ""));
        }
        exportVo.setReceiverName(orderOutputDo.getOutputReceiverName());
        exportVo.setPostCode(orderOutputDo.getOutputPostCode().replaceAll("-", ""));
        orderOutputDo.setOutputAddress(orderOutputDo.getOutputAddress().trim().replaceAll("\\n", "").replaceAll("　", " ").replaceAll("－", "-").replaceAll("−", "-").replaceAll("－", "-"));
        if (orderOutputDo.getOutputArea() != null) {
            String area = StringsUtil.getJpAreaByEnglishCode(orderOutputDo.getOutputArea());
            orderOutputDo.setOutputAddress((orderOutputDo.getOutputAddress().contains(area) ? "" : area)
                    + orderOutputDo.getOutputAddress().trim().replaceAll("\\n", ""));
        } else {

        }
        if (orderOutputDo.getOutputAddress().length() <= 22) {
            exportVo.setAddress1(orderOutputDo.getOutputAddress());
        } else if (orderOutputDo.getOutputAddress().length() <= 37) {
            exportVo.setAddress1(orderOutputDo.getOutputAddress().substring(0, 22));
            exportVo.setAddress2(orderOutputDo.getOutputAddress().substring(22));
        } else if (orderOutputDo.getOutputAddress().length() <= 60) {
            exportVo.setAddress1(orderOutputDo.getOutputAddress().substring(0, 22));
            exportVo.setAddress2(orderOutputDo.getOutputAddress().substring(22, 37));
            exportVo.setE3(orderOutputDo.getOutputAddress().substring(37));
        } else {
            exportVo.setAddress1(orderOutputDo.getOutputAddress().substring(0, 22));
            exportVo.setAddress2(orderOutputDo.getOutputAddress().substring(22, 37));
            exportVo.setE3(orderOutputDo.getOutputAddress().substring(37, 60));
            exportVo.setE4(orderOutputDo.getOutputAddress().substring(60));
        }
        exportVo.setReceiverName(orderOutputDo.getOutputReceiverName());

        StringBuilder sku = new StringBuilder();
        StringBuilder storageSku = new StringBuilder();

//        exportVo.setCommoditySku("【" + sku.toString() + "】");
        exportVo.setCommoditySku(orderOutputDo.getCommoditySku());
//        exportVo.setStorageSku(orderOutputDo.getStorageSku());

//        String position = this.getPosition(rackProductCountMap);
//        exportVo.setStorageSkuKane(position);

        exportVo.setOrderNo(orderOutputDo.getOrderNo());
//        if (orderOutputDo.getDeliveryDate() != null)
//            if (orderOutputDo.getDeliveryDate().getTime() < System.currentTimeMillis()) {
//                Calendar calendar = Calendar.getInstance();
//                calendar.add(Calendar.DAY_OF_YEAR, 1);
//                exportVo.setDeliveryDate(TimeUtils.formatDate(calendar.getTime(), "yyyy/MM/dd"));
//            } else {
//                exportVo.setDeliveryDate(TimeUtils.formatDate(orderOutputDo.getDeliveryDate(), "yyyy/MM/dd"));
//            }
//        exportVo.setDeliveryTimeCode(TimeUtils.getYamatoDTime(orderOutputDo.getDeliveryTime()));
        if (orderOutputDo.getCod() != 0 && orderOutputDo.getCod() != 0) {
            exportVo.setExpressNo("2");
            exportVo.setE16("0");
            exportVo.setE17(orderOutputDo.getCod() + "");
        }
        exportVo.setE18("3");//是否显示序号
        exportVo.setCount("1");
        return exportVo;

    }

}
